package com.solairen.myapplication.Pager.LoginPager;

import static com.solairen.myapplication.Pager.Util.UtilName.*;
import static com.solairen.myapplication.Pager.LoginPager.LoginStatus.*;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.solairen.myapplication.MainActivity;
import com.solairen.myapplication.R;
import com.solairen.myapplication.data.MainVM;
import com.solairen.myapplication.net.BaseModel;
import com.solairen.myapplication.net.HttpResult;
import com.solairen.myapplication.utils.ApiResponseCallback;
import com.solairen.myapplication.utils.MD5;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginNameActivity extends AppCompatActivity {
    private static final String server = "http://ads.zhen-guo.top:8080";
    private EditText etUsername, etPassword;
    private Button btnLogin, btnWechatLogin, btnQqLogin, btnPhoneLogin;
    private TextView btnRegister, btnForget;
    private Toast currentToast;

    private MainVM mainVM;

    /**
     * 保存登录状态到SharedPreferences
     *
     * @param username
     * @param password
     */
    private void saveLoginInfo(String username, String password) {
        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        Editor editor = sharedPreferences.edit();
        editor.putString(KEY_NAME, username);
        editor.putString(KEY_PWD, password);
        editor.putBoolean(KEY_LOGIN_STATUS, true);
        editor.apply();
    }

    /**
     * 检查登陆状态，实现自动跳转
     */
    private void checkAndAutoLogin() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        if (prefs.getBoolean(KEY_LOGIN_STATUS, false)) {
            String username = prefs.getString(KEY_NAME, "");
            String password = prefs.getString(KEY_PWD, "");

            // todo:实现自动跳转
            // 跳转首页
            Intent intent = new Intent(LoginNameActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();


        }
    }

//    private void showToast(String message, int duration) {
//        if (currentToast != null) {
//            currentToast.cancel(); // 取消当前正在显示的Toast
//        }
//        currentToast = Toast.makeText(LoginNameActivity.this, message, duration);
//        currentToast.show();
//    }

    private void showToast(String message, int duration) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (currentToast != null) {
                    currentToast.cancel(); // 取消当前正在显示的Toast
                }
                currentToast = Toast.makeText(LoginNameActivity.this, message, duration);
                currentToast.show();
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_name);
        checkAndAutoLogin();
        initViews();

        // fixme:将kotlin改成了java，使用OKhttp，kotlin实在看不懂啊qwq
        // 监听数据
//        mainVM = new ViewModelProvider(this).get(MainVM.class);
//        mainVM.getLoginLD().observe(this, baseModelHttpResult -> {
//            if (baseModelHttpResult instanceof HttpResult.Success) {
//                // 保存登录信息
//                saveLoginInfo(etUsername.getText().toString().trim(), etPassword.getText().toString().trim());
//
//                // 跳转首页
//                Intent intent = new Intent(LoginNameActivity.this, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                startActivity(intent);
//                finish();
//            } else if (baseModelHttpResult instanceof HttpResult.Failure) {
//                Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
//            } else {
//                Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
//            }
//        });

    }


    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);

        btnRegister = findViewById(R.id.tv_go_register);


        /******************************************设置监听*****************************************/

        /*******登录按钮点击事件********/
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String username = etUsername.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                String hashedPassword = MD5.encrypt(password);
                if (username.isEmpty() || password.isEmpty()) {
                    // 显示错误提示信息
                    showToast("用户名和密码不得为空", Toast.LENGTH_SHORT);
                } else {
                    // todo 发包收包POST
                    // FIXME: 2024/3/5 发起登录
//                    mainVM.login(username, password);

                    // FIXME: 改成了Okhttp请求qwq

                    loginRequest(new ApiResponseCallback() {
                        @Override
                        public void onSuccess(Response response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().string());
                                String code = jsonObject.getString("code");
                                String message = jsonObject.getString("message");
                                String token = jsonObject.getString("data");

                                if (code.equals("0")) {
                                    showToast("登录成功", Toast.LENGTH_SHORT);
                                    Log.d("login", message);
                                    saveToken(token);
                                    // 保存登录信息
                                    saveLoginInfo(etUsername.getText().toString().trim(), etPassword.getText().toString().trim());
                                    Intent intent = new Intent(LoginNameActivity.this, MainActivity.class);
                                    intent.putExtra("code", code);
                                    startActivity(intent);
                                    finish();

                                } else {
                                    // 注册失败，显示错误信息
                                    String errorMessage = jsonObject.getString("Message"); // 替换为实际错误信息字段
                                    showToast(errorMessage, Toast.LENGTH_SHORT);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Log.d("response", e.toString());
                                showToast("账号或密码错误",Toast.LENGTH_SHORT);

                            }
                        }

                        @Override
                        public void onFailure(IOException e) {
                            showToast("连接失败", Toast.LENGTH_SHORT);
                        }
                    }, username, hashedPassword);

                }
            }
        });

        /*******注册按钮点击事件********/
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("这是注册", Toast.LENGTH_SHORT);
                //跳转注册页面
                startActivity(new Intent(LoginNameActivity.this, RegisterNameActivity.class));
            }
        });


    }

    public void loginRequest(ApiResponseCallback callback, String username, String password) {
        Log.d("username", username);
        Log.d("password", password);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient httpClient = new OkHttpClient();
                    MediaType text = MediaType.parse("application/x-www-form-urlencoded");
                    String textContent = "username=" + username + "&password=" + password;
                    RequestBody requestBody = RequestBody.create(text, textContent);

                    /**********记得改下地址，现在的地址是测试用的*************/
                    String url = server + "/user/login";
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();

                    Call call = httpClient.newCall(request);
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        // success
                        callback.onSuccess(response);
                        Log.d("awa", response.toString() + "------------------");
//                        Log.d("awa", response.body().string() + "------------------");
                    } else {
                        callback.onFailure(new IOException("出错啦！" + response.code()));
                        Log.d("qwq", "失败了" + response.toString());
                    }
                } catch (IOException e) {
                    callback.onFailure(e);
                }
            }
        }).start();
    }


    private void saveToken(String token) {
        // 这里根据你的需求存储Token，例如SharedPreferences
        SharedPreferences.Editor editor = getSharedPreferences("MyPreferences", MODE_PRIVATE).edit();
        editor.putString("user_token", token);
        editor.apply();
    }


}